<template>
  <el-drawer size="80%" :title="dialogTitle" v-model="dialogVisible" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="主任务" prop="mainTaskId">
        <TaskTitleSelect
          v-model="formData.mainTaskName"
          @change="handleTaskTitleChange"
          :disabled="updateDisabled || createDisabled || viewDisabled"
        />
      </el-form-item>
      <el-form-item label="子任务名称" prop="taskTitle">
        <el-input v-model="formData.taskTitle" :disabled="updateDisabled || viewDisabled" placeholder="请输入子任务名称" />
      </el-form-item>
      
      <el-form-item label="执行人" prop="operatorUserId">
        <UserSelect
          v-model="formData.operatorUserId"
          @node-change="handleUserChange" :disabled="updateDisabled  || viewDisabled"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="operatorUserName" v-show="false">
        <el-input v-model="formData.operatorUserName" :disabled="updateDisabled || viewDisabled" />
      </el-form-item>
      <el-form-item label="优先级" prop="priorityType">
        <el-radio-group v-model="formData.priorityType" :disabled="updateDisabled || viewDisabled" placeholder="请选择优先级">
          <el-radio 
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_PRIORITY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate" >
        <el-date-picker
style="width: 100%;" :disabled="updateDisabled || viewDisabled"
          v-model="formData.endDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择结束日期"
        />
      </el-form-item>
      <!-- <el-form-item label="拒绝理由" prop="reason">
        <el-input v-model="formData.reason" type="textarea" />
      </el-form-item> -->
      <!-- <el-form-item label="实际完成日期" prop="actualEndDate" >
        <el-date-picker
          v-model="formData.actualEndDate"
          type="date"
          disabled
          value-format="YYYY-MM-DD"
          placeholder="选择实际完成日期"
        />
      </el-form-item>
      
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="formData.taskStatus" placeholder="请选择任务状态" disabled>
          <el-option 
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item v-if="viewDisabled && formData.taskStatus==2" label="拒绝理由" prop="reason">
        <el-input v-model="formData.reason" :disabled="true" :rows="6" type="textarea" />
      </el-form-item>
      <el-form-item v-else label="进度描述" prop="taskDescription">
        <el-input v-model="formData.taskDescription" type="textarea" :disabled="viewDisabled" placeholder="请输入子任务个办理进度和工作内容" :rows="12" />
      </el-form-item>
      <!-- <el-form-item label="相关附件" >
        <OaFileManager :folderDisabled="true" :header="!viewDisabled"  :initial-file-ids="formData.files" @file-select-success="fileSelectScccess"  />
      </el-form-item> -->
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" v-if="!viewDisabled" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { SubtasksApi, SubtasksVO } from '@/api/oa/subtasks'
import { MainTasksApi } from '@/api/oa/maintasks'
import TaskTitleSelect from '@/components/TaskTitleSelect/index.vue'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 子任务管理 表单 */
defineOptions({ name: 'SubtasksForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改 preview - 查看
const mainTaskList = ref<any[]>([]) // 主任务列表

// 获取主任务列表
const getMainTaskList = async () => {
  try {
    const res = await MainTasksApi.getMainTasksPageAll({ pageNo: 1, pageSize: 100 })
    mainTaskList.value = res.list
    
  } catch (error) {
    console.error('获取主任务列表失败:', error)
    message.error('获取主任务列表失败')
  }
}

// 处理任务主题变更
const handleTaskTitleChange = (task) => {
  if (task) {
    formData.value.mainTaskId = task.id
    formData.value.mainTaskName = task.taskName
  } else {
    formData.value.mainTaskId = undefined
    formData.value.mainTaskName = undefined
  }
}
// ... existing code ...

// 处理执行人变更
const handleUserChange = (user: any) => {
  if (user) {
    formData.value.operatorUserId = user.id
    formData.value.operatorUserName = user.nickname
  } else {
    formData.value.operatorUserId = undefined
    formData.value.operatorUserName = undefined
  }
}

const formData = ref({
  id: undefined as number | undefined,
  taskTitle: undefined as string | undefined,
  mainTaskId: undefined as number | undefined,
  mainTaskName: undefined as string | undefined,
  operatorUserId: undefined as number | undefined,
  operatorUserName: undefined as string | undefined,
  priorityType: undefined as number | undefined,
  endDate: undefined as number | undefined,
  actualEndDate: undefined as number | undefined,
  taskStatus: undefined as number | undefined,
  files: undefined as string | undefined,
  taskDescription: undefined as string | undefined,
  reason: undefined as string | undefined,
})
const formRules = reactive({
  taskTitle: [{ required: true, message: '任务主题不能为空', trigger: 'change' }],
  mainTaskId: [{ required: true, message: '主任务不能为空', trigger: 'change' }],
  operatorUserId: [{ required: true, message: '执行人不能为空', trigger: 'change' }],
  priorityType: [{ required: true, message: '优先级不能为空', trigger: 'change' }],
  endDate: [{ required: true, message: '结束日期不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const updateDisabled = ref(false) // 输入框是否禁用
const createDisabled = ref(false) // 输入框是否禁用
const viewDisabled = ref(false) // 查看时输入框是否禁用

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取主任务列表
  await getMainTaskList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true 
    try {
      formData.value = await SubtasksApi.getSubtasks(id)
    } finally {
      formLoading.value = false
    }
  } 
  console.log(t('action.' + type))
  if(type=== 'preview'){
    updateDisabled.value = false
    createDisabled.value = false
    viewDisabled.value = true
  } else if(type === 'update'){
    updateDisabled.value = true
    createDisabled.value = false 
    viewDisabled.value = false
  }
  if(type === 'create' && formData.value.mainTaskId !== undefined 
  && formData.value.mainTaskId > 0){
    createDisabled.value = true
    updateDisabled.value = false 
    viewDisabled.value = false
  }
}
defineExpose({ open, formData }) // 提供 open 方法，用于打开弹窗
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SubtasksVO
    if (formType.value === 'create') {
      await SubtasksApi.createSubtasks(data)
      message.success(t('common.createSuccess'))
    } else {
      await SubtasksApi.updateSubtasks(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    taskTitle: undefined,
    mainTaskId: undefined,
    operatorUserId: undefined,
    operatorUserName: undefined,
    priorityType: undefined,
    endDate: undefined,
    actualEndDate: undefined,
    taskStatus: undefined,
    files: undefined,
    taskDescription: undefined,
  }
  formRef.value?.resetFields()
}
</script>